package com.LachesismStorm.lachesism.downloader;

import com.LachesismStorm.lachesism.core.util.AsyncUtil;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class hypnotube2VideoDownloader {

    public static void main(String[] args) {
        ArrayList<String> pageUrls = new ArrayList<>();
        pageUrls.add("https://hypnotube.com/channels/28/sissy-training-hypnotube/views/");
        for (int i = 2; i < 20; i++) {
//            String url = "https://hypnotube.com/search/popper/views/page" + i + ".html";
            String url = "https://hypnotube.com/channels/28/sissy-training-hypnotube/views/page" + i + ".html";
            pageUrls.add(url);
        }
        System.out.println("开始执行了"+pageUrls);
        for (String pageUrl : pageUrls) {
            AsyncUtil.executeAsync(() -> {
                a(pageUrl);
            });
        }

    }

    @SneakyThrows
    public static void a(String pageUrl) {
        // 获取页面中符合条件的所有链接
        List<String> links = getLinksFromPage(pageUrl);
        // 输出所有链接并处理每个链接
        for (String link : links) {
            System.out.println("正在处理链接: " + link);
            // 获取并打印视频链接和文件名
            String[] videoInfo = getVideoUrlFromPage(link);
            if (videoInfo != null && videoInfo.length == 2) {
                String videoUrl = videoInfo[0];
                String fileName = videoInfo[1];
                System.out.println("找到视频链接: " + videoUrl);
                System.out.println("视频文件名: " + fileName);
//                File file = Paths.get("/Users/yuno/Downloads/video", fileName).toFile();
                File file = Paths.get("/Users/yuno/Downloads/video", fileName).toFile();
                // 下载视频
                if (!file.exists()) {
                    downloadVideo(videoUrl, fileName);
                }
            } else {
                System.out.println("未找到视频链接");
            }
        }
    }

    // 获取页面中符合选择器规则的所有 href 链接
    public static List<String> getLinksFromPage(String pageUrl) throws IOException {
        List<String> links = new ArrayList<>();
        Document document = Jsoup.connect(pageUrl)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Accept-Language", "zh-CN,zh-Hans;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Cookie", "_ga=GA1.1.286448684.1736210202; _ga_X9SNEJRE4V=GS1.1.1741567374.18.1.1741567461.0.0.0; PHPSESSID=h1bja8gegco3gkon67g7map03n")
                .header("Pragma", "no-cache")
                .header("Referer", "https://hypnotube.com/search/popper/page2.html")
                .header("Sec-Fetch-Dest", "document")
                .header("Sec-Fetch-Mode", "navigate")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15")
                .get();

        String selector = "body > section.page-wrap > section.content-sec > div > div:nth-child(2) > div > div > main > div > div > div > div > div:nth-child(n) > div > a:nth-child(1)";
        Elements linkElements = document.select(selector);
        // 遍历所有元素，提取 href 属性
        for (Element linkElement : linkElements) {
            String href = linkElement.attr("href");
            if (!href.isEmpty()) {
                links.add(href);  // 存入列表
            }
        }
        return links;
    }

    // 获取页面的 HTML 内容并提取视频链接和文件名
    public static String[] getVideoUrlFromPage(String pageUrl) throws IOException {
        // 获取页面的HTML内容
        Document document = Jsoup.connect(pageUrl)
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Accept-Language", "zh-CN,zh-Hans;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Cookie", "_ga=GA1.1.286448684.1736210202; _ga_X9SNEJRE4V=GS1.1.1741567374.18.1.1741567461.0.0.0; PHPSESSID=h1bja8gegco3gkon67g7map03n")
                .header("Pragma", "no-cache")
                .header("Referer", pageUrl)
                .header("Sec-Fetch-Dest", "document")
                .header("Sec-Fetch-Mode", "navigate")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15")
                .get();

        // 获取 og:title 的 content 属性
        String title = "";
        Elements metaElements = document.select("meta[property=og:title]");
        if (!metaElements.isEmpty()) {
            title = metaElements.attr("content");  // 获取 content 属性
        }

        // 定义选择器规则，提取 video 标签下的 source 标签中的 src 属性
        String videoSelector = "video#plyr_player > source";

        // 获取符合条件的 source 标签
        Elements sourceElements = document.select(videoSelector);

        // 如果找到符合条件的 source 标签，获取 src 属性
        if (!sourceElements.isEmpty()) {
            Element sourceElement = sourceElements.first();
            String videoSrc = sourceElement.attr("src");  // 获取 src 属性

            // 提取文件名并返回视频链接和文件名
            String fileName = title + ".mp4";  // 拼接文件名
            return new String[]{videoSrc, fileName};  // 返回视频链接和文件名
        }
        // 如果没有找到视频链接，返回空字符串
        return null;
    }

    // 下载视频并保存到本地
    public static void downloadVideo(String videoUrl, String fileName) throws IOException {
        // 目标文件夹路径
//        String downloadDir = "/Users/yuno/Downloads/video";
        String downloadDir = "/Users/yuno/Downloads/video";
        // 确保目标文件夹存在
        File dir = new File(downloadDir);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                System.err.println("无法创建目标目录: " + downloadDir);
                return;
            }
        }
        // 设置视频文件保存路径
        File videoFile = new File(downloadDir, fileName);
        // 获取视频链接
        URL url = new URL(videoUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
        // 获取输入流
        try (InputStream inputStream = connection.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(videoFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("视频下载完成：" + videoFile.getAbsolutePath());
        }
    }
}
